import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

enum SecureStorageKey {
  token,
}

class SecureStorage {
  SecureStorage._() {
    AndroidOptions getAndroidOptions() => const AndroidOptions(
          encryptedSharedPreferences: true,
        );
    _storage = FlutterSecureStorage(aOptions: getAndroidOptions());
  }

  late final FlutterSecureStorage _storage;

  static final SecureStorage _instance = SecureStorage._();
  factory SecureStorage() => _instance;

  Future<Result<String?>> get(SecureStorageKey key) async {
    try {
      return Result.ok(await _storage.read(key: key.name));
    } on Exception catch (e) {
      return Result.error(e);
    }
  }

  Future<Result<void>> save(SecureStorageKey key, String value) async {
    try {
      await _storage.write(key: key.name, value: value);
      return const Result.ok(null);
    } on Exception catch (e) {
      return Result.error(e);
    }
  }

  Future<Result<void>> delete(SecureStorageKey key) async {
    try {
      await _storage.delete(key: key.name);
      return const Result.ok(null);
    } on Exception catch (e) {
      return Result.error(e);
    }
  }
}
